import copy
import json
import traceback

from django.db.models import Q

from Puer.publicUtils.public_method import get_page_start_end
from models import *
from Puer.constant import constant
from django.http import HttpResponse
import datetime
from django.db import transaction


# 获取分类商品列表
def get_kind_of_product(request):
    try:
        type1 = request.GET.get("type1")
        type2 = request.GET.get("type2")
        # 版型
        model = request.GET.get("model")
        # 价格 order/顺序;reverse_order/倒序
        price = request.GET.get("price")
        data = []
        product_type_results = Producttype.objects.filter(typename=type1, typename2=type2)

        for product_type in product_type_results:
            product_kind_result = Productkind.objects.filter(typeid=product_type.typeid)
            for product_kind in product_kind_result:
                product_obj = Product.objects.filter(productid=product_kind.productid,
                                                     status=constant.PRODUCT_STATE)
                if product_obj:
                    data.append(
                        {  # id
                            "product_id": product_obj[0].productid,
                            # 编号
                            "product_no": product_obj[0].productno,
                            # 商品名称
                            "product": product_obj[0].name,
                            # 价格
                            "price": "%.2f" % float(product_obj[0].price),
                            # 版型
                            "model": product_obj[0].model,
                            # # 库存
                            # "stock": int(product_obj.stock),
                            # 缩略图
                            "thumbnail": "%s%s" % (constant.FILE_ADDRESS, product_obj[0].thumbnail)
                        }
                    )

        if model != constant.MODEL:
            data_deepcopy = copy.deepcopy(data)
            for product in data:
                if model != product.get("model"):
                    data_deepcopy.remove(product)
            data = data_deepcopy

        if price != constant.PRICE:
            if price == constant.ORDER:
                data = sorted(data, key=lambda x: x["price"])
            elif price == constant.REVERSE_ORDER:
                data = sorted(data, key=lambda x: x["price"], reverse=True)
            else:
                return HttpResponse(json.dumps(["failure", "The price type is not correct"]),
                                    content_type=constant.CONTENT_TYPE)
        return HttpResponse(json.dumps(data))
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()

        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 商品详情
def get_product_detail(request):
    try:
        product_id = request.GET.get("productId")
        user_id = request.GET.get("userid")
        data = {}
        data1 = []
        product_obj = Product.objects.get(productid=product_id)
        shopping_cart_result = Shoppingcart.objects.filter(userid=user_id)
        for cart in shopping_cart_result:
            pro = Product.objects.filter(productid=cart.productid, status=constant.PRODUCT_STATE)
            if pro:
                # shop = Shoppingcart.objects.filter(productid=pro[0].productid)
                # if shop:
                #     if shop[0].cartid not in data1:
                #         data1.append(shop[0].cartid)
                data1.append(cart.number)

        product_swiper_result = Productswiper.objects.filter(productid=product_id).order_by("number")
        # product_standard_result = Productstandard.objects.filter(productid=product_id)
        data.update({
            "product_detail": {
                "product_id": product_obj.productid,
                'refer_price': "%.2f" % float(product_obj.referenceprice) if product_obj.referenceprice else constant.DEFAULT_MONEY,
                "product_name": product_obj.name,
                "product_price": "%.2f" % float(product_obj.price) if product_obj.price else constant.DEFAULT_MONEY,
                "product_detail": ["%s%s" % (constant.FILE_ADDRESS, product_obj.detail)],
                # 'product_stock': sum([int(product_standard.stock) for product_standard in product_standard_result]),

                # 商品轮播图
                "product_carousel": ["%s%s" % (constant.FILE_ADDRESS, product_swiper.image) for product_swiper in
                                     product_swiper_result],

                # "product_color": [product_standard.color for product_standard in product_standard_result],
                # "product_size": [product_standard.name for product_standard in product_standard_result]
            },
            "shopping_cart_num": sum(data1)
        })
        return HttpResponse(json.dumps(data))
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 查询新品预售商品
def get_new_products(request):
    try:
        data = []
        open_booking_result = Openbooking.objects.all().order_by("-no")
        for product in open_booking_result:
            product_obj = Product.objects.get(productid=product.productid,
                                              status=constant.PRODUCT_STATE)
            if product_obj:
                data.append({
                    "product_id": product_obj.productid,
                    "product_name": product_obj.name,
                    "product_price": "%.2f" % float(product_obj.price),
                    "product_thumbnail": "%s%s" % (constant.FILE_ADDRESS, product_obj.thumbnail)
                })
        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 查询限时商品
def get_time_limit_products(request):
    try:
        data = []
        flash_sale_result = Flashsale.objects.all().order_by("-no")
        for product in flash_sale_result:
            product_obj = Product.objects.get(productid=product.productid,
                                              status=constant.PRODUCT_STATE)
            if product_obj:
                data.append({
                    "product_id": product_obj.productid,
                    "product_name": product_obj.name,
                    # 现价
                    "product_price": "%.2f" % float(product_obj.price),
                    # 原价
                    "product_reference_price":
                        "%.2f" % float(product_obj.referenceprice) if product_obj.referenceprice else constant.DEFAULT_MONEY,
                    "product_thumbnail": "%s%s" % (constant.FILE_ADDRESS, product_obj.thumbnail)
                })
        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 商品库存检查
def product_stock_checked(request):
    try:
        data = []
        product_id = request.GET.get("productId")
        product_color = request.GET.get("color")
        # product_size = request.GET.get("size")
        if not Product.objects.get(productid=product_id):
            return HttpResponse(json.dumps(["failure", "The product was obtained"]), content_type=constant.CONTENT_TYPE)
        # if product_color:
        #     product_standard_result = Productstandard.objects.filter(productid=product_id,
        #                                                              color=product_color)
        #     for product_standard in product_standard_result:
        #         data.append({
        #             "size": product_standard.name,
        #             "stock": product_standard.stock
        #         })
        # if product_size:
        #     product_standard_result = Productstandard.objects.filter(productid=product_id,
        #                                                              name=product_size)
        #     for product_standard in product_standard_result:
        #         data.update({
        #             "color": product_standard.color,
        #             "stock": product_standard.stock
        #         })
        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# ----------------------------------------PC------------------------------------------
# 普通商品的添加
def add_product(request):
    get_product_name = request.POST.get('productName')
    # get_product_stock = request.POST.get('productStock')
    get_status = int(request.POST.get('status'))

    get_product_price = request.POST.get('productPrice')
    get_product_reference_price = request.POST.get('referPrice', None)
    get_product_model = request.POST.get('productModel')
    get_product_brand = request.POST.get('productBrand')
    get_product_thumbnail = request.FILES.get('thumbnail')
    get_product_detail = request.FILES.get('detail')
    get_product_typename = request.POST.get('productGroup1')
    get_product_typename2 = request.POST.get('productGroup2')
    # get_product_standard = request.POST.get('productSize')
    get_product_swiper_image1 = request.FILES.get('image1')
    get_product_swiper_image2 = request.FILES.get('image2')
    get_product_swiper_image3 = request.FILES.get('image3')
    get_product_swiper_image4 = request.FILES.get('image4')
    get_product_swiper_image5 = request.FILES.get('image5')
    # get_product_active = request.POST.get('ProductActive')
    get_product = Product.objects.filter(name=get_product_name, status=constant.PROCESSED)

    if get_product:
        return HttpResponse(json.dumps(["failure", "do not add again"]), content_type=constant.CONTENT_TYPE)

    if get_status == 1:
        with transaction.atomic():
            try:
                product = Product()
                product.name = get_product_name
                product.brand = get_product_brand
                product.price = get_product_price
                if get_product_reference_price:
                    product.referenceprice = get_product_reference_price
                product.model = get_product_model
                # product.stock = get_product_stock
                product.thumbnail = get_product_thumbnail
                product.detail = get_product_detail
                product.status = constant.PRODUCT_STATE
                product.onlinetime = datetime.datetime.now()
                product.productno = 10000 + len(Product.objects.all())
                product.save()
                product_id = product.productid
            except:
                error_msg = "%s" % traceback.format_exc()
                return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
            # get_product = Product.objects.filter(name=get_product_name, status=constant.PRODUCT_STATE)[0]

            get_product_type = \
                Producttype.objects.filter(typename=get_product_typename, typename2=get_product_typename2)[0]
            product_type_id = get_product_type.typeid
            try:
                # 添加规格
                Productkind.objects.create(productid=product_id, typeid=product_type_id, no=constant.PRODUCT_SORT)

            except:
                error_msg = "%s" % traceback.format_exc()
                return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    if get_status == 2:
        with transaction.atomic():
            try:
                product = Product()
                product.name = get_product_name
                product.brand = get_product_brand
                product.price = get_product_price
                if get_product_reference_price:
                    product.referenceprice = get_product_reference_price
                product.model = get_product_model
                # product.stock = get_product_stock
                product.thumbnail = get_product_thumbnail
                product.detail = get_product_detail
                product.status = constant.PRODUCT_STATE
                product.onlinetime = datetime.datetime.now()
                product.productno = 10000 + len(Product.objects.all())
                product.save()
                product_id = product.productid
                if Openbooking.objects.filter(productid=product.productid):
                    return HttpResponse(json.dumps(["failure", 'this product belong open_book product']),
                                        content_type=constant.CONTENT_TYPE)
                if Flashsale.objects.filter(productid=product.productid):
                    return HttpResponse(json.dumps(["failure", 'do not add again']), content_type=constant.CONTENT_TYPE)
                Flashsale.objects.create(
                    productid=product.productid,
                    no=1

                )
            except:
                error_msg = "%s" % traceback.format_exc()
                return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    if get_status == 3:
        with transaction.atomic():
            try:
                product = Product()
                product.name = get_product_name
                product.brand = get_product_brand
                product.price = get_product_price
                if get_product_reference_price:
                    product.referenceprice = get_product_reference_price
                product.model = get_product_model
                # product.stock = get_product_stock
                product.thumbnail = get_product_thumbnail
                product.detail = get_product_detail
                product.status = constant.PRODUCT_STATE
                product.onlinetime = datetime.datetime.now()
                product.productno = 10000 + len(Product.objects.all())
                product.save()
                product_id = product.productid
                if Flashsale.objects.filter(productid=product.productid):
                    return HttpResponse(json.dumps(["failure", 'this product belong flashsale product']),
                                        content_type=constant.CONTENT_TYPE)
                if Openbooking.objects.filter(productid=product.productid):
                    return HttpResponse(json.dumps(["failure", 'do not add again']), content_type=constant.CONTENT_TYPE)
                Openbooking.objects.create(
                    productid=product.productid,
                    no=1

                )
            except:
                error_msg = "%s" % traceback.format_exc()
                return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)

    # for product_standard in json.loads(get_product_standard):
    #
    #     try:
    #         Productstandard.objects.create(
    #             productid=product_id,
    #             # 列表元素顺序 颜色,尺码,库存
    #             color=product_standard[0],
    #             name=product_standard[1],
    #             stock=product_standard[2])
    #     except:
    #         error_msg = "%s" % traceback.format_exc()
    #         return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    swiper_image_list = [get_product_swiper_image1, get_product_swiper_image2, get_product_swiper_image3,
                         get_product_swiper_image4, get_product_swiper_image5]

    try:
        image_num = 1
        for get_product_swiper_image in swiper_image_list:
            product_swiper = Productswiper()
            product_swiper.productid = product_id
            product_swiper.image = get_product_swiper_image
            product_swiper.number = image_num
            product_swiper.save()

            image_num += 1
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)

    return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)


#  添加限时商品
def add_time_product(request):
    try:
        get_product_id = int(request.GET.get('productId'))
        if not get_product_id:
            return HttpResponse(json.dumps(["failure", 'productId is empty']), content_type=constant.CONTENT_TYPE)
        product = Product.objects.filter(productid=get_product_id)
        if not product:
            return HttpResponse(json.dumps(["failure", 'no have product']), content_type=constant.CONTENT_TYPE)
        if not product[0].referenceprice:
            return HttpResponse(json.dumps(["failure", 'must have referenceprice']), content_type=constant.CONTENT_TYPE)
        if Openbooking.objects.filter(productid=get_product_id):
            return HttpResponse(json.dumps(["failure", 'this product belong to openbooking product']),
                                content_type=constant.CONTENT_TYPE)
        if Flashsale.objects.filter(productid=get_product_id):
            return HttpResponse(json.dumps(["failure", 'do not add again']),
                                content_type=constant.CONTENT_TYPE)

        Flashsale.objects.create(productid=get_product_id, no=1 + len(Flashsale.objects.all()))
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


#  添加新品预售
def add_new_product(request):
    try:
        get_product_id = int(request.GET.get('productId'))
        if not get_product_id:
            return HttpResponse(json.dumps(["failure", 'productId is empty']), content_type=constant.CONTENT_TYPE)
        pro = Product.objects.filter(productid=get_product_id)
        if not pro:
            return HttpResponse(json.dumps(["failure", 'not have this product']), content_type=constant.CONTENT_TYPE)
        if Flashsale.objects.filter(productid=get_product_id):
            return HttpResponse(json.dumps(["failure", 'this product is flash product']),
                                content_type=constant.CONTENT_TYPE)
        product = Openbooking.objects.filter(productid=get_product_id)
        if product:
            return HttpResponse(json.dumps(["failure", 'do not add again']), content_type=constant.CONTENT_TYPE)

        Openbooking.objects.create(productid=get_product_id, no=1 + len(Flashsale.objects.all()))
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 下架限时商品
def delete_time_product(request):
    try:
        get_product_id = request.GET.get('productId')
        if not get_product_id:
            return HttpResponse(json.dumps(["failure", 'productId is empty']), content_type=constant.CONTENT_TYPE)
        flash = Flashsale.objects.filter(productid=int(get_product_id))
        if not flash:
            return HttpResponse(json.dumps(["failure", 'not have this product']), content_type=constant.CONTENT_TYPE)
        Flashsale.objects.filter(productid=int(get_product_id)).delete()
        Product.objects.filter(productid=get_product_id).update(status=constant.PRODUCT_STATE_OBTAINED)
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 下架预售商品
def delete_open_product(request):
    try:
        get_product_id = request.GET.get('productId')
        if not get_product_id:
            return HttpResponse(json.dumps(["failure", 'productId is empty']), content_type=constant.CONTENT_TYPE)
        open_book = Openbooking.objects.filter(productid=int(get_product_id))
        if not open_book:
            return HttpResponse(json.dumps(["failure", 'not have this product']), content_type=constant.CONTENT_TYPE)
        Openbooking.objects.filter(productid=int(get_product_id)).delete()
        Product.objects.filter(productid=get_product_id).update(status=constant.PRODUCT_STATE_OBTAINED)
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 商品删除

def delete_product(request):
    try:
        product_id = request.GET.get("productId")
        Product.objects.filter(productid=product_id).update(status=constant.PRODUCT_STATE_OBTAINED)
        if Flashsale.objects.filter(productid=product_id):
            Flashsale.objects.filter(productid=product_id).delete()
        if Openbooking.objects.filter(productid=product_id):
            Openbooking.objects.filter(productid=product_id).delete()
        if Productkind.objects.filter(productid=product_id):
            Productkind.objects.filter(productid=product_id).delete()
        # 删除轮播图
        Productswiper.objects.filter(productid=product_id).delete()
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 商品详情
def get_product_details(request):
    try:
        data = []
        product_id = int(request.GET.get("productId"))
        product_result = Product.objects.filter(productid=product_id, status=constant.PRODUCT_STATE)

        if Product.objects.filter(productid=product_id) and Flashsale.objects.filter(productid=product_id):
            product_status = 2
        elif Product.objects.filter(productid=product_id) and Openbooking.objects.filter(productid=product_id):
            product_status = 3
        else:
            product_status = 1
        for product in product_result:
            # 商品类型
            product_type = []
            # 商品参加的活动
            product_activity = []
            # 商品规格
            product_standard = []

            # 商品详情
            product_detail = "%s%s" % (constant.FILE_ADDRESS, product.detail)
            # 商品缩略图
            product_thumbnail = "%s%s" % (constant.FILE_ADDRESS, product.thumbnail)

            product_kind_result = Productkind.objects.filter(productid=product_id)
            # 商品分类关联查询
            for product_kind in product_kind_result:
                product_type_result = Producttype.objects.filter(typeid=product_kind.typeid)
                if product_type_result:
                    product_type = [product_type_result[0].typename, product_type_result[0].typename2]

            # 商品规格关联查询
            # product_standard_result = Productstandard.objects.filter(productid=product_id)
            # 商品轮播图关联查询
            product_swiper_result = Productswiper.objects.filter(productid=product_id).order_by("number")
            # 商品轮播图
            product_swiper_list = ["%s%s" % (constant.FILE_ADDRESS, product_swiper.image)
                                   for product_swiper in product_swiper_result]
            # for product_standard_info in product_standard_result:
            #     product_standard.append({
            #         # 商品规格颜色
            #         'product_color': product_standard_info.color,
            #         # 商品规格
            #         'product_size': product_standard_info.name,
            #         # 商品库存
            #         'product_stock': product_standard_info.stock,
            #         # 商品规格ID
            #         'product_standard_id': product_standard_info.standardid
            #     })

            row = {
                # 1.商品名称
                'product_name': product.name,
                # 2.商品编号
                'product_no': product.productno,
                # # 3.商品总量
                # 'product_number': product.stock,
                # 4.商品价格
                'product_price': "%.2f" % float(product.price),
                # 5.商品参考价格
                'product_refer': "%.2f" % float(product.referenceprice) if product.referenceprice else None,
                # 6.商品品牌
                'product_brand': product.brand,
                # 7.商品版型
                'product_model': product.model,
                # 8.商品分组
                'product_type': product_type,

                # 9.商品id
                'product_id': product.productid,
                # 'product_standard': product_standard,
                # 10.商品详情
                'product_detail': product_detail,
                # 11.商品缩略图
                'product_thumbnail': product_thumbnail,
                # 商品轮播图
                'product_img': product_swiper_list,
                # 商品类型
                'product_status': product_status
            }
            data.append(row)

        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 商品数量新增
def product_number_addition(request):
    try:
        product_id = int(request.GET.get("productId"))
        product_addition_num = json.loads(request.GET.get("num"))
        product = Product.objects.get(productid=product_id, status=constant.PRODUCT_STATE)
        if product:
            with transaction.atomic():

                add_standard_stock_list = [int(product_addition[-1]) for product_addition in product_addition_num
                                           if product_addition[-1]]
                all_add_standard_stick = sum(add_standard_stock_list)
                # 更新商品总库存量
                product_stock = int(all_add_standard_stick) + int(product.stock)
                Product.objects.filter(productid=product_id, status=constant.PRODUCT_STATE).update(stock=product_stock)
                # 更新商品下各个规格的库存
                for product_addition in product_addition_num:
                    if product_addition[-1]:
                        product_standard = Productstandard.objects.get(standardid=product_addition[0])
                        product_standard_stock = int(product_standard.stock) + int(product_addition[-1])
                        product_standard.stock = product_standard_stock
                        product_standard.save()
            return HttpResponse(json.dumps("success"), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 商品列表
def product_list(request):
    try:
        # 筛选条件
        get_keyword = request.GET.get('keyword', None)
        get_page = request.GET.get('page')
        get_row = request.GET.get('row')
        get_status = int(request.GET.get("status"))
        # 全部
        data2 = []
        data3 = []
        data4 = []
        search_product_result = []
        if get_status == 1:
            flash_product = Flashsale.objects.all()
            for flash in flash_product:
                data2.append(flash.productid)
            open_book = Openbooking.objects.all()
            for book in open_book:
                data3.append(book.productid)
            search_product_result = Product.objects.filter(status=constant.PRODUCT_STATE).filter(
                ~Q(productid__in=data2)).filter(~Q(productid__in=data3))
            for id in search_product_result:
                data4.append(id)

        # 限时
        if get_status == 2:
            flash_sale = Flashsale.objects.all()
            product_id = []
            for flash in flash_sale:
                product_id.append(flash.productid)
            search_product_result = Product.objects.filter(productid__in=product_id, status=constant.PRODUCT_STATE)

        # 预售
        if get_status == 3:
            open_booking = Openbooking.objects.all()
            product_id = []
            for book in open_booking:
                product_id.append(book.productid)
            search_product_result = Product.objects.filter(productid__in=product_id, status=constant.PRODUCT_STATE)
        if get_keyword and get_status == 1:
            search_product_result = Product.objects.filter(Q(name__contains=get_keyword) |
                                                           Q(brand__contains=get_keyword),
                                                           status=constant.PRODUCT_STATE).filter(
                ~Q(productid__in=data2)).filter(~Q(productid__in=data3))
        if get_status == 2 and get_keyword:
            flash_sale = Flashsale.objects.all()
            product_id = []
            for flash in flash_sale:
                product_id.append(flash.productid)
            search_product_result = Product.objects.filter(productid__in=product_id,
                                                           status=constant.PRODUCT_STATE).filter(
                Q(name__contains=get_keyword) |
                Q(brand__contains=get_keyword)
            )
        if get_keyword and get_status == 3:
            open_booking = Openbooking.objects.all()
            product_id = []
            for book in open_booking:
                product_id.append(book.productid)
            search_product_result = Product.objects.filter(productid__in=product_id,
                                                           status=constant.PRODUCT_STATE).filter(
                Q(name__contains=get_keyword) |
                Q(brand__contains=get_keyword)
            )

        start, stop = get_page_start_end(get_page, get_row, search_product_result)
        data = []
        data_count = len(search_product_result)
        for count in range(start, stop):
            if count >= data_count:
                break
            product_thumbnail = "%s%s" % (constant.FILE_ADDRESS, search_product_result[count].thumbnail)
            row = {
                # 商品id
                'product_id': search_product_result[count].productid,
                # 商品编号
                'product_no': search_product_result[count].productno,
                # 商品名称
                'product_name': search_product_result[count].name,
                # 商品缩略图
                'product_thumbnail': product_thumbnail,
                # # 在架/库存
                # 'product_stock': str(search_product_result[count].stock),
                # 商品价格
                'product_price': "%.2f" % float(search_product_result[count].price),
            }
            data.append(row)

        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 修改商品

def update_product_information(request):
    get_product_id = int(request.POST.get('productId'))
    get_product_brand = request.POST.get('productBrand')
    get_product_name = request.POST.get('productName')
    get_product_price = request.POST.get('productPrice')
    get_product_reference_price = request.POST.get('referPrice', None)
    get_product_model = request.POST.get('productModel')
    get_product_typename = request.POST.get('productGroup1', None)
    get_product_typename2 = request.POST.get('productGroup2', None)
    # get_product_active = request.POST.get('ProductActive')
    get_product_thumbnail = request.FILES.get('thumbnail', None)
    get_product_detail = request.FILES.get('detail', None)
    swiper_image1 = request.FILES.get('image1', None)
    swiper_image2 = request.FILES.get('image2', None)
    swiper_image3 = request.FILES.get('image3', None)
    swiper_image4 = request.FILES.get('image4', None)
    swiper_image5 = request.FILES.get('image5', None)

    get_product = Product.objects.filter(name=get_product_name, status=constant.PROCESSED)
    if get_product:
        for product in get_product:
            if product.productid != get_product_id:
                return HttpResponse(json.dumps(["failure", "do not add again"]),
                                    content_type=constant.CONTENT_TYPE)
    with transaction.atomic():
        try:

            product_detail = Product.objects.get(productid=get_product_id)

            product_detail.name = get_product_name
            product_detail.brand = get_product_brand
            product_detail.price = get_product_price
            product_detail.model = get_product_model
            if get_product_reference_price:
                product_detail.referenceprice = get_product_reference_price
            if get_product_thumbnail:
                product_detail.thumbnail = get_product_thumbnail
            if get_product_detail:
                product_detail.detail = get_product_detail
            product_detail.save()
        except:
            error_msg = "%s" % traceback.format_exc()
            return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
        try:

            img_list = [swiper_image1, swiper_image2, swiper_image3, swiper_image4, swiper_image5]
            for img in img_list:
                if img:
                    product_swiper_res = Productswiper.objects.get(productid=get_product_id,
                                                                   number=img_list.index(img) + 1)
                    product_swiper_res.image = img
                    product_swiper_res.save()

        except:
            error_msg = "%s" % traceback.format_exc()
            return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)

        if get_product_typename and get_product_typename2:
            try:
                get_product_type = \
                    Producttype.objects.filter(typename=get_product_typename, typename2=get_product_typename2)[0]
                product_type_id = get_product_type.typeid
                Productkind.objects.filter(productid=get_product_id).update(typeid=product_type_id)
            except:
                error_msg = "%s" % traceback.format_exc()
                return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)


#  商品分类查询
def find_product(request):
    # 筛选条件
    get_type_name1 = request.GET.get('productGroup1')
    get_type_name2 = request.GET.get('productGroup2')
    get_page = request.GET.get('page')
    get_row = request.GET.get('row')

    if get_type_name1 == constant.ALL and get_type_name2 == constant.ALL:
        try:
            search_product_result = Product.objects.filter(status=constant.PRODUCT_STATE)
            start, stop = get_page_start_end(get_page, get_row, search_product_result)
            data = []
            data_count = len(search_product_result)
            for count in range(start, stop):
                if count >= data_count:
                    break
                product_thumbnail = "%s%s" % (constant.FILE_ADDRESS, search_product_result[count].thumbnail)
                row = {
                    # 商品编号
                    'product_no': search_product_result[count].productno,
                    # 商品id
                    'product_id': search_product_result[count].productid,
                    # 商品名
                    'product_name': search_product_result[count].name,
                    # 商品缩略图
                    'product_thumbnail': product_thumbnail,
                    # # 在架/库存
                    # 'product_stock': str(search_product_result[count].stock),
                    # 商品价格
                    'product_price': "%.2f" % float(search_product_result[count].price),
                }
                data.append(row)
            return HttpResponse(json.dumps([data, data_count]), content_type='application/json')
        except:
            error_msg = "%s" % traceback.format_exc()
            return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    else:
        try:
            product_type = Producttype.objects.filter(typename=get_type_name1, typename2=get_type_name2)
            product_type_id = product_type[0].typeid
            data1 = []
            data2 = []
            data3 = []
            product_list = Productkind.objects.filter(typeid=product_type_id)
            for product in product_list:
                data1.append(product.productid)
            flash_product = Flashsale.objects.all()
            for flash in flash_product:
                data2.append(flash.productid)
            open_book = Openbooking.objects.all()
            for book in open_book:
                data3.append(book.productid)
            search_product_result = Product.objects.filter(productid__in=data1, status=constant.PRODUCT_STATE).filter(
                ~Q(productid__in=data2)).filter(~Q(productid__in=data3))
            start, stop = get_page_start_end(get_page, get_row, search_product_result)
            data = []
            data_count = len(search_product_result)
            for count in range(start, stop):
                if count >= data_count:
                    break
                product_thumbnail = "%s%s" % (constant.FILE_ADDRESS, search_product_result[count].thumbnail)
                row = {
                    # 商品编号
                    'product_no': search_product_result[count].productno,
                    # 商品编号
                    'product_id': search_product_result[count].productid,
                    # 商品名
                    'product_name': search_product_result[count].name,
                    # 商品缩略图
                    'product_thumbnail': product_thumbnail,
                    # 在架/库存
                    # 'product_stock': str(search_product_result[count].stock),
                    # 商品价格
                    'product_price': "%.2f" % float(search_product_result[count].price),
                }
                data.append(row)
            return HttpResponse(json.dumps([data, data_count]), content_type='application/json')
        except:
            error_msg = "%s" % traceback.format_exc()
            return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 删除分类下的子商品

def delete_son_product(request):
    try:
        get_type_name1 = request.GET.get('productGroup1')
        get_type_name2 = request.GET.get('productGroup2')
        get_product_id = request.GET.get('productId')

        product_type = Producttype.objects.filter(typename=get_type_name1, typename2=get_type_name2)
        product_type_id = product_type[0].typeid

        Productkind.objects.filter(productid=int(get_product_id), typeid=product_type_id).delete()

        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 添加轮播图

def add_index_swiper_image(request):
    try:
        # swiper = Indexswiper.objects.all()
        # print(len(swiper))
        # if len(swiper) > 4:
        #     return HttpResponse(json.dumps("failure"), content_type=constant.CONTENT_TYPE)

        get_img = request.FILES.get('img')

        index_swiper = Indexswiper()
        index_swiper.image = get_img
        index_swiper.save()
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)

    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 展示轮播图

def show_index_swiper_img(request):
    try:
        index_swipers = Indexswiper.objects.all()
        data = []
        for index_swiper in index_swipers:
            dic = {
                'id': index_swiper.id,
                'img': "%s%s" % (constant.FILE_ADDRESS, index_swiper.image)
            }
            data.append(dic)
        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 删除轮播图

def delete_index_swiper_img(request):
    try:
        get_swiper_id = request.GET.get('swiperId')
        Indexswiper.objects.filter(id=int(get_swiper_id)).delete()
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)

